﻿//Force setting jQuery support cross domain.
//This line mostly has effective in IE

var userId = "";
userId = readCookie("userId");
if (userId == "") {
    window.location.href = '../Profile/Login';
}
var updateId = "";
jQuery.support.cors = true;
selectedText = "";
selectedTextArea = null;
function getSelectedText(id) {
    var range = $('textarea#' + id).getSelection();
    var st = range.text;
    return st;
}
function addKeyword(id, messflowid) {
    selectedTextArea = $('textarea#make_keyword' + id); //.replaceSelection('<' + selectedText + '>', true);
    $('#make_keyword').attr("messflowid", messflowid);
    $('#errorMakekeyword').html("");
    $("#btnSaveKeyWord .cus_button_mid").text("Save");
    $('#make_keyword').jqmShow();
    $('#make_keyword').find(".countable").val("");
    if (selectedText != "") {
        $('#make_keyword div#keyword').show();
        $('#txtKeyword').hide();
        $('#make_keyword div#keyword').html(selectedText);
        $('.cus_input').css("display", "none");
    }
    else {
        $('#make_keyword div#keyword').hide();
        $('#txtKeyword').show();
        $('#txtKeyword').val("");
        $('.cus_input').css("display", "block");

    }
}

//function getURLParameter(name) {
//    return decodeURI(
//                (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
//                );
//}
//function checkUniqueness(name, campaignid) {

//}
$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    }
});
var Text2 = new Object();
var arrCurrentCountry = new Array(); // current selected country
var arrMessagesFlows = new Array();
var arrKeywordValue = new Array();
//Bind data to Campaign field
function getListCampain() {
        $.getJSON(gb_servicePath+'/campaign/list/summary.json',
            function (json1) {
            if (json1.StatusCode == 200) {
                $.each(json1.ReturnData, function (i, val) {
                    if (i == 0) {
                        var o = $("<option selected='selected' id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                        $("#campaign_selection").find(".customStyleSelectBoxInner").html(val.Name);
                    } else {
                        var o = $("<option id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                    }

                    $("#campaign_selection").find("select").append(o);
                });
                if (getURLParameter("id").toString() == "null") {
                    getListAudience(true);
                }
            }
         });
}
function getListMessagesType() {
    $.getJSON(gb_servicePath+'/component/list.json?productname=Text 2',
    function (json1) {
        if (json1.StatusCode == 200) {
            $.each(json1.ReturnData, function (i, val) {
                if (val.Name == "Win") {
                    for (var i = 0; i < val.MessageflowType.length; i++) {
                        var o = $("#messflows_temp").clone();
                        $(o).attr("id", "messagestype" + val.MessageflowType[i].Id);
                        $(o).addClass("messagesflowtype");
                        $(o).attr("value", val.MessageflowType[i].Id);
                        $(o).css("display", "block");
                        $(o).find("strong").html("Message For " + val.MessageflowType[i].Name);
                        $("#make_keyword_detail").find("ul").append(o);
                    }
                   // $(".content_box").jScrollPane();
                }
            });
        }
    });
}
//Bind data to Target Audience
function getListAudience(wait) {
    $("#btn_target_audience_template").css("display", "none");
    $("#btn_target_audience_template_2").css("display", "none");

    $.ajax({ url: gb_servicePath + '/group/list.json?userid=' + userId + "&campaignid=" + $("#campaign_selection").find("option:selected").attr("id"),
        dataType: 'json',
        data: '',
        async: wait,
        success: function (json1) {
            if (json1.StatusCode == 200) {

                $("#countries0 #list_audience").find(".list_count").each(function () {
                    if ($(this).attr("id") != "btn_target_audience_template") {
                        $(this).remove();
                    }
                });

                $.each(json1.ReturnData, function (i, val) {
                    var o = $("#btn_target_audience_template").clone();
                    $(o).css("display", "block");
                    $(o).find("input").attr("value", val.Name);
                    $(o).attr("id", val.ID);
                    $(o).find("span").html(val.Name);
                    if ($("#countries0 #list_audience").find(".jspPane").length > 0) {
                        $("#countries0 #list_audience").find(".jspPane").append(o);
                    } else {
                        $("#countries0 #list_audience").append(o);
                    }
                    var oo = $("#btn_target_audience_template_2").clone();
                    $(oo).css("display", "block");
                    $(oo).find("input").attr("value", val.Name);
                    $(oo).attr("id", 'c_' + val.ID);
                    $(oo).attr("value", val.ID);
                    $(oo).find("span").html(val.Name);
                    $("#list_audience_make_keyword").find(".jspPane").append(oo);

                    if (i == 0) {
                        var o = $("<option selected='selected' id='" + val.ID + "' value='" + val.Name + "' >" + val.Name + "</option>");
                        $("#audience_selection").find(".customStyleSelectBoxInner").html(val.Name);
                    } else {
                        var o = $("<option id='" + val.ID + "' value='" + val.Name + "' >" + val.Name + "</option>");
                    }

                    $("#audience_selection").find("select").append(o);

                });
                $('.label_check, .label_radio, .label_check_ip').click(function () {
                    setupLabel();
                });
                $('#countries0 #list_audience').jScrollPane();

            }
        }
    });
}
//function getListAudience() {
//    $("#btn_target_audience_template").css("display", "none");
//    $.getJSON(gb_servicePath + '/group/list.json',
//                function (json1) {
//                    if (json1.StatusCode == 200) {
//                        $.each(json1.ReturnData, function (i, val) {                           
//                            if (i == 0) {
//                                var o = $("<option selected='selected' id='" + val.ID + "' value='" + val.Name + "' >" + val.Name + "</option>");
//                                $("#audience_selection").find(".customStyleSelectBoxInner").html(val.Name);
//                            } else {
//                                var o = $("<option id='" + val.ID + "' value='" + val.Name + "' >" + val.Name + "</option>");
//                            }

//                            $("#audience_selection").find("select").append(o);
//                        });
//                    }
//                });
//}
function parseDate(str) {
    return new Date(Date.parse(str));
}
function FormatToDate(str) {
    var date = str.substr(6).replace(')', '').replace('/', '');
    var sendTime = new Date(parseInt(date));
    var month = sendTime.getUTCMonth() + 1;
    if (month < 9) {
        month = '0' + (sendTime.getUTCMonth() + 1);
    }
    var day = sendTime.getUTCDate();
    if (day < 9) {
        day = '0' + (sendTime.getUTCDate());
    }
    var year = sendTime.getUTCFullYear();


    return month + "/" + day + "/" + year;
}
function FormatToTime(str) {
    var date = str.substr(6).replace(')', '').replace('/', '');
    var sendTime = new Date(parseInt(date));

    var hour = sendTime.getUTCHours();
    var minute = sendTime.getUTCMinutes();

    return format2Digi(hour) + ":" + format2Digi(minute);
}
function format2Digi(num) {
    if (num > 9) return num
    else return "0" + num;
}
function getKeywordById(kwid) {
    $.getJSON(gb_servicePath + '/keyword/ID/' + kwid + '.json', {},
                function (json2) {
                    if (json2.StatusCode == 200) {
                        var data = json2.ReturnData;
                        arrKeywordValue[data.Id + "_"] = data;
                    }
                });
}

function getTextInstance(id, type) {
    $.getJSON(gb_servicePath + '/Text2/ID/' + id + '.json?type=' + type,
                    {}, function (json) {
                        if (json.StatusCode == 200) {
                            var data = json.ReturnData;
                            if (data == null) {

                                alert("Wrong text id");

                                return;
                            }
                            Text2.id = data.Id;
                            // updateId = data.AlertCollectionSummary.Id;
                            $("#sl_campaign").val(data.Campaign.Name).attr("selected", "selected");
                            $("#span_sl_campaign").html(data.Campaign.Name);
                            $("#cbWin").val(data.WinTypeID).attr("selected", "selected");
                            $('#cbWin_selection .customStyleSelectBoxInner').html($('#cbWin option[name=' + data.WinTypeID + ']').val());
                            $('#ddlperiodUnitName option[name=' + data.EntriesAllowedInPeriod.Key + ']').attr("selected", "selected");
                            $('#periodUnitName_selection .customStyleSelectBoxInner').html($('#ddlperiodUnitName option[name=' + data.EntriesAllowedInPeriod.Key + ']').val());

                            if (location.hash == "#copy") {
                                $('#txtName').val('');
                            }
                            else {
                                $("#txtName").val(data.Name);
                                $("#sl_campaign").css('display', 'none');
                                $("#sl_campaign").next().css('display', 'none');
                                $("#sl_campaign").after('<strong id="ddlCampAdd">' + $("#sl_campaign").find(":selected").text() + '</strong>');
                            }
                            if (data.IsActive == 1) {
                                $('label.label_check_ip input#chkActive').attr('checked', 'checked');
                            } else {
                                $('label.label_check_ip input#chkActive').removeAttr('checked');

                            }

                            getListAudience(false);
                            setupLabel();
                            var strAudience = "";
                            $.each(data.Alertcollection.Audience, function (i, val) {
                                strAudience += val.ID + ",";
                            });

                            $('#txtNumberOfParticipants').val(data.ParticipatorsEstimate);
                            $('input:radio[name=selection]').filter('[value=' + data.WinSelectionTypeID + ']').attr('checked', true);
                            $('input:radio[name=selection]').filter('[value=' + data.WinSelectionTypeID + ']').parent().addClass('r_on');
                            $('#send_on_date').val(FormatToDate(data.StartTime));
                            $('#send_on_time').val(FormatToTime(data.StartTime));

                            $('#valid_until_date').val(FormatToDate(data.EndTime));
                            $('#valid_until_time').val(FormatToTime(data.EndTime));
                            $('#txt_prizeexpiration').val(FormatToDate(data.PrizeExpirationDate));


                            // if (data.AlertInstanceSummary.MessageFlows.length > 0) {
                            $.each(data.MessageFlows, function (i, val) {
                                var oMess = new Object();
                                oMess.Id = val.Id;
                                oMess.countryId = val.Country.Id;
                                oMess.mediaId = val.Media.Id;
                                oMess.languageId = val.Language.Id;
                                oMess.messagesBody = val.Messagebody;
                                oMess.messageflowType = { Id: val.MessageflowType.Id, Name: val.MessageflowType.Name };
                                // oMess.Name = val.Name;
                                oMess.keywordlist = val.KeywordIDList;
                                var keywordvalues = new Array();
                                oMess.keywordvalues = keywordvalues;
                                arrMessagesFlows[oMess.countryId + "_" + oMess.languageId + "_" + oMess.mediaId] = oMess;
                                for (var k = 0; k < oMess.keywordlist.length; k++) {
                                    getKeywordById(oMess.keywordlist[k]);
                                }
                            })
                            //}

                            var country = "";
                            var delivery = "";
                            var arrCountry = new Array();
                            $.each(data.Alertcollection.Preference, function (i, val) {
                                country += val.Preference.Country.Name + " ( " + val.Preference.Language.Name + " ) " + "<br/>"
                                delivery += val.Media.Name;
                                //find exist country
                                var o = new Object();
                                var needInsert = true;
                                for (var i = 0; i < arrCountry.length; i++) {
                                    if (arrCountry[i].Country.Id == val.Preference.Country.Id) {
                                        o = arrCountry[i];
                                        needInsert = false;
                                        break;
                                    }
                                }
                                if (needInsert) {
                                    var cont = new Object();
                                    cont.Id = val.Preference.Country.Id;
                                    cont.Name = val.Preference.Country.Name;
                                    o.Country = cont;
                                }

                                var timezone = new Object();
                                timezone.Id = val.Preference.Timezone.Id;
                                timezone.Name = val.Preference.Timezone.Name.split(")")[0] + ")"; ;
                                o.Timezone = timezone;

                                var languages = new Array();
                                if (!needInsert) {
                                    languages = o.Language;
                                }

                                var oLang = new Object();
                                var medias = new Array();
                                for (var i = 0; i < languages.length; i++) {
                                    if (languages[i].Id == val.Preference.Language.Id) {
                                        medias = languages[i].Media;
                                        oLang = languages[i];
                                    }
                                }

                                if (medias.length == 0) {
                                    //insert new languages
                                    oLang.Id = val.Preference.Language.Id;
                                    oLang.Name = val.Preference.Language.Name;
                                    oLang.selected = true;
                                    oLang.CountryPreId = val.Preference.Id;
                                    languages.push(oLang);
                                }
                                //search for media 
                                var omedia = new Object();
                                omedia.Id = val.Media.Id;
                                omedia.Name = val.Media.Name;
                                omedia.selected = true;

                                var needInsertMedia = true;
                                for (var i = 0; i < medias.length; i++) {
                                    if (medias[i].Id == omedia.Id) {
                                        needInsertMedia = false;
                                        break;
                                    }
                                }
                                if (needInsertMedia) {
                                    medias.push(omedia);
                                }
                                oLang.Media = medias;
                                if (needInsert) {
                                    o.Language = languages;
                                    arrCountry.push(o);
                                }

                            })

                            //Prize Level
                            $('.list_winners #now_1').remove();
                            $.each(data.WinnersNum, function (j, valNum) {
                                addItemNOW(valNum);
                                $('.text_input_level').numeric();
                                $('.text_input_number').numeric();
                            });
                            for (var i = 0; i < arrCountry.length; i++) {
                                addCountryPre(arrCountry[i]);
                            }
                            $("#list_audience").find(".list_count").each(function (index) {
                                if (strAudience == "" && index == 0) {
                                    $(this).find(".label_check").addClass("c_on");
                                    $(this).find(".label_check input").attr('checked', true);
                                }
                                if (strAudience.indexOf($(this).attr("id")) >= 0) {
                                    $(this).find(".label_check").addClass("c_on");
                                    $(this).find(".label_check input").attr('checked', true);
                                }
                            });



                        } else {
                            if (isBug) {
                                alert("Wrong alert Id");
                            }
                        }
                    }
                );
}

//add country in list country 
function addCountryPre(o) {
    o.CountryName = o.Country.Name;
    arrCurrentCountry.push(o);
    if ($("#country_Item" + o.Country.Id).length > 0) {
        $("#country_Item" + o.Country.Id).remove();
    }
    var oCoun = $("#country_temp").clone();
    $(oCoun).attr("data", JSON.stringify(o));
    $(oCoun).find(".col_country").html(o.Country.Name);
    $(oCoun).attr("id", "country_Item" + o.Country.Id);
    $(oCoun).attr("value", o.Country.Id);
    $(oCoun).css("display", "block");

    for (var i = 0; i < o.Language.length; i++) {
        if (o.Language[i].selected == true) {
            if (i % 2 == 1) {
                var olang = $("<div value='" + o.Language[i].Id + "' class='alt'>" + o.Language[i].Name + "</div>");
                $(oCoun).find(".col_language").append(olang);
            } else {
                var olang = $("<div value='" + o.Language[i].Id + "'>" + o.Language[i].Name + "</div>");
                $(oCoun).find(".col_language").append(olang);
            }


            var arrMedias = o.Language[i].Media;
            var strmedia = "";
            var strmediaid = "";
            for (var j = 0; j < arrMedias.length; j++) {
                if (arrMedias[j].selected == true) {
                    strmedia += arrMedias[j].Name + ", ";
                    strmediaid += arrMedias[j].Id;
                }
            }

            if (strmedia.substring(strmedia.length - 2, strmedia.length) == ", ") {
                strmedia = strmedia.substring(0, strmedia.length - 2);
            }
            var omedia;
            if (i % 2 == 1) {
                omedia = $("<div value='" + strmediaid + "' class='alt'>" + strmedia + "</div>");
            } else {
                omedia = $("<div value='" + strmediaid + "'>" + strmedia + "</div>");
            }
            $(oCoun).find(".col_method").append(omedia);
        }
    }
    var ohide = $("<div class='hide row_hide'>&nbsp;</div>")
    $(oCoun).find(".col_language").append(ohide);
    var ohidemedia = $("<div class='hide row_hide'><a href='#messages' class='i_delete'>Delete</a></div>");
    $(oCoun).find(".col_method").append(ohidemedia);

    $("#listCountries").find(".jspPane").append(oCoun);

    refreshScrollbarListCountry();

    $('.list_row').jScrollPane({ animateScroll: true });
    $(oCoun).click(function () {
        $('#messages').removeClass('hide');
        $("#box_select_countries").css("display", "none");
        $('.rows').removeClass('hover');
        $(this).addClass('hover');
        $('.row_hide').addClass('hide');
        $(this).find('.row_hide').removeClass('hide');
        $('.col_method').css('width', '105px');
        $('.list_row').jScrollPane({ animateScroll: true });
        //  alert(jQuery.parseJSON($(this).attr("data")).Country.Name);
        //remove all old $(".mess_detail")
        $("#messflows").find(".mess_detail").each(function () {
            if ($(this).attr("id") != "mess_detail_temp") {
                $(this).remove();
            }
        });
        $(".jqEasyCounterMsg").remove();
        var o = jQuery.parseJSON($(this).attr("data"));
        addMessagesflow(o);
        $('.countable').jqEasyCounter({
            'maxChars': 500,
            'maxCharsWarning': 161,
            'msgFontSize': '11px',
            'msgFontColor': '#595959',
            'msgTextAlign': 'right',
            'msgWarningColor': '#F00',
            'msgAppendMethod': 'insertBefore'
        });
        $('.jqEasyCounterMsg').corner();

        $('#messages textarea.countable').mouseup(function () {
            var id = $(this).attr('id');
            selectedText = getSelectedText(id);
        });

        $('#Span3').click(function () {
            if (selectedTextArea && selectedText != '') selectedTextArea.replaceSelection('<' + selectedText + '>', true);
          //  $('#make_keyword').jqmHide();
        });

    });

    $(".i_delete").click(function () {
        $("#box_confirm").jqmShow();
    });


}

//recalculate height of list country
function refreshScrollbarListCountry() {
    if ($('.rows').length == 2) {
        $('div#listCountries div.jspContainer').css('height', '63px');
    }
    else if ($('.rows').length == 3) {
        $('div#listCountries div.jspContainer').css('height', '123px');
    }
    else if ($('.rows').length == 4) {
        $('div#listCountries div.jspContainer').css('height', '183px');
    } else if ($('.rows').length < 2) {
        $('div#listCountries div.jspContainer').css('height', '0px');
    }
}

// add messages flows to messages box
function addMessagesflow(ob) {
    for (var j = 0; j < ob.Language.length; j++) {
        var medias = ob.Language[j].Media;
        if (ob.Language[j].selected == true) {
            for (var i = 0; i < medias.length; i++) {
                if (medias[i].selected == true) {
                    var o = $("#mess_detail_temp").clone();
                    $(o).find(".mess_detail_txt").html(ob.Country.Name + "," + ob.Language[j].Name + "," + medias[i].Name);
                    $(o).attr("id", "mess_detail_" + ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id);
                    $(o).attr("messflowid", ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id);
                    $(o).css("display", "block");
                    $(o).attr("value", j + "_" + i);
                    $(o).find("textarea").attr("id", "txt_" + j + "_" + i);
                    //alert("messages flows : " + arrMessagesFlows[ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id].messagesBody);
                    $("#messflows").find(".jspPane").append(o);
                    if (arrMessagesFlows[ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id] != undefined) {
                        var obb = arrMessagesFlows[ob.Country.Id + "_" + ob.Language[j].Id + "_" + medias[i].Id];
                        $(o).find("textarea").attr("instanceid", obb.Id);
                        // edit alert or create new alert with
                        $(o).find("textarea").val(obb.messagesBody);
                        var keywordidlist = "";
                        for (var k = 0; k < obb.keywordlist.length; k++) {
                            keywordidlist += obb.keywordlist[k];
                            if (obb.keywordvalues[k] != undefined) {
                                var oK = $("#btKeywordTemp").clone();
                                $(oK).find(".btparent").removeClass("with_close");
                                $(oK).find(".btparent").addClass("key_disable");
                                $(oK).attr("value", obb.keywordlist[k]);
                                $(oK).find(".key_button_mid").html(obb.keywordvalues[k]);
                                $(oK).css("display", "block");
                                $(oK).attr("id", "btKeyword" + obb.keywordlist[k]);
                                $(o).find(".keywordcollection").append(oK);
                                $(oK).find(".key_button_right").click(function () {
                                    if (!$(this).parent().hasClass("key_disable")) {
                                        removeKeyword($(this).prev().attr("id"), userId, getURLParameter("id"));
                                        $(this).parent().parent().remove();
                                    }
                                });
                            } else if (arrKeywordValue[obb.keywordlist[k] + "_"] != undefined) {
                                var oK = $("#btKeywordTemp").clone();
                                $(oK).find(".btparent").removeClass("with_close");
                                $(oK).find(".btparent").addClass("key_disable");
                                $(oK).attr("value", obb.keywordlist[k]);
                                $(oK).find(".key_button_mid").html(arrKeywordValue[obb.keywordlist[k] + "_"].Name);
                                $(oK).find(".key_button_mid").click(function () {
                                    if (!$(this).parent().hasClass("key_disable")) {
                                        editKeyword($(this).parent().parent().attr("value"));
                                    }
                                });
                                $(oK).css("display", "block");
                                $(oK).attr("id", "btKeyword" + obb.keywordlist[k]);
                                $(o).find(".keywordcollection").append(oK);
                                $(o).find(".key_button_right").attr("thismessID", obb.Id);
                                $(oK).find(".key_button_right").click(function () {
                                    if (!$(this).parent().hasClass("key_disable")) {
                                        removeKeyword($(this).parent().parent().attr("value"), userId, $(this).attr("thismessID"));
                                        $(this).parent().parent().remove();
                                    }
                                });

                            }
                        }

                    }
                    $(o).attr("keywordidlist", keywordidlist);
                }
            }
        }

    }
    $(".make_keyword").css("cursor", "pointer");
    $(".make_keyword").click(function () {
        if (!$(this).hasClass("edit_disable")) {
            addKeyword($(this).parent().attr("value"), $(this).parent().attr("messflowid"));
        }
    });
   
    $('#make_keyword').jqm({ modal: true });
    $('#comfirm_blk').jqm();
    $('#comfirm_blk').jqmAddClose($('#confirm_cancel'));

    $('#make_keyword').css('right', ($(window).width() - 1100) / 2 + 120);
    $("#box_alert").jqm();

    $('#box_confirm').jqm({ trigger: '.i_delete' });
    $('#box_confirm2').jqm({ trigger: '.btn_delete' });
    $('#box_confirm2').jqmAddClose($('#btnCancel_confirm2'));
    $('#make_keyword').jqmAddClose($('.btn_Close'));
    $('#make_keyword').jqmAddClose($('.btn_Cancel'));
   // $('#make_keyword').jqmAddClose($('.btn_Save'));
    $('#box_alert').jqmAddClose($('#btnOk_boxalert'));
    $('#box_confirm').jqmAddClose($('#btnCancel_confirm1'));


    $("#messflows").jScrollPane({ animateScroll: true });
    if ($(".mess_detail").length > 4) {
        $(".mess_detail").css("padding-right", '5px');
    }
    else {
        $(".mess_detail").css("padding-right", '15px');
    }

    $('#btn_Edit').click(function () {
        //$('.make_keyword').attr('href', '#make_keyword');
        $('.edit_disable').css('display', 'none');
        $('.edit_enable').css('display', 'block');
        $('.mess_detail textarea').removeAttr('disabled');
        $('.mess_detail textarea').addClass('textarea_enable');
       // $('a.btn_delete').css('visibility', 'visible');
        $('#btn_SaveMessage').removeClass('hide');
        $('#btn_Cancel').removeClass('hide');
        $(this).addClass('hide');
        $('.itemfilter').hide();
        $('.btn_unleashed').show();
        $('.btn_freetix').show();
        $(".btparent").removeClass("key_disable");
        $(".btparent").addClass("with_close");
        $('#btn_Cancel').click(function () {
            $.fancybox.close();
        });
    });

}

function sortCountryTable(isDec) {
    if (isDec) {
        $("#btSortCountry").attr("sort", "-1");
        $("#btSortCountry").find("img").rotate(0);
        var arr = arrCurrentCountry.objSort("CountryName", -1);
        $("#listCountries").find(".jspPane").find(".rows").each(function () {
            if ($(this).attr("id") != "country_temp") {
                $(this).remove();
            }
        });
        arrCurrentCountry = new Array();
        for (var i = 0; i < arr.length; i++) {
            addCountryPre(arr[i]);
        }
    } else {
        $("#btSortCountry").attr("sort", "1");
        $("#btSortCountry").find("img").rotate(180);
        var arr = arrCurrentCountry = arrCurrentCountry.objSort("CountryName", 1);
        $("#listCountries").find(".jspPane").find(".rows").each(function () {
            if ($(this).attr("id") != "country_temp") {
                $(this).remove();
            }
        });
        arrCurrentCountry = new Array();
        for (var i = 0; i < arr.length; i++) {
            addCountryPre(arr[i]);
        }
    }

}
function validateKeyword() {
    var ex = true;
    /*    if ($("#keyword").css("display") != "none") {
    if ($("#keyword").html() == "") {
    $('#errorMakekeyword').html("All field should be entered ");
    $('#errorMakekeyword').css('color', '#ff5050');
    ex = false;
    }
    } else {
    */
    var keyw = $("#txtKeyword").val()
        if (keyw == "") {
            $('#errorMakekeyword').html("Keyword should be entered");
            $('#errorMakekeyword').css('color', '#ff5050');
            return false;
        }
 /*   };
    $(".messagesflowtype").each(function () {
        if ($(this).find(".countable").val() == "") {
            $('#errorMakekeyword').html("All field should be entered ");
            $('#errorMakekeyword').css('color', '#ff5050');
            ex = false;
        }
    }); */

        var arrCountryId = $("#make_keyword").attr("messflowid").split("_");
        var countryid = arrCountryId[0];  //countryid is the same as it’s parent message flow
        var campaignid = $("#campaign_selection").find("option:selected").attr("id");

        $.ajax({
            url: gb_servicePath + "/keyword/lookup.json?name=" + keyw + '&campaignid=' + campaignid + '&countryid=' + countryid,
            crossDomain: "true",
            type: "GET",
            async: false,
            "dataType": 'json',
            success: function (data) {
                if (data.ReturnData.length > 0) {
                    $('#errorMakekeyword').html(keyw + " is already defined in the system. Please choose another keyword.");
                    $('#errorMakekeyword').css('color', '#ff5050');
                    ex = false;
                }
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error in GEMAPI/keyword/lookup.json");
                }
            }
        });

        return ex;
    }

function buildKeyWorldCollection() {
    var keyword = new Object();
    if ($("#keyword").css("display") != "none") {
        keyword.name = $("#keyword").html();
    } else {
        keyword.name = $("#txtKeyword").val();
    };

    keyword.componentid = "5"; // Here function is component for win
    var audience = new Array();
    audience.push($("#audience_selection").find("option:selected").attr("id"));
    keyword.grouplist = audience;
    keyword.campaignid = $("#campaign_selection").find("option:selected").attr("id"); //campaign id is the same as the campaign id of the alert collection

    var arrCountryId = $("#make_keyword").attr("messflowid").split("_");
    keyword.countryid = arrCountryId[0];  //countryid is the same as it’s parent message flow
    keyword.languageid = arrCountryId[1]; //languageid is the same as it’s parent message flow
    keyword.mediaid = arrCountryId[2]; //media is the same as it’s parent message flow 

    var messagelist = new Array();
    $(".messagesflowtype").each(function () {
        var message1 = new Object();
        message1.messageflowtypeid = $(this).attr("value"); // message type id
        message1.messagebody = $(this).find(".countable").val(); // message body
        if (message1.messagebody != "") {
            messagelist.push(message1); //add message1 to keyword object    
        }
    });

    keyword.messagelist = messagelist;

    return keyword;
}
function buildMessageFlowCollection(messflowid) {
    if (messflowid == undefined) return;
    var messageflow = new Object();
    messageflow.messagebody = $("#mess_detail_" + messflowid).find(".textarea_enable").val();
    messageflow.messageflowtypeid = "1"; // Here messageflowtypeid is 1 (alert msgs; it's 5 for keyword msgs)

    var keywordids = new Array();
    /*if ($("#mess_detail_" + messdetailid).find(".button_b").length == 0) {
    keywordids.push("1");    
    }*/
    $("#mess_detail_" + messflowid).find(".button_b").each(function () {
        if ($(this).attr("id") != "btKeywordTemp") {
            keywordids.push($(this).attr("value"));
        }
    });
    /*if (keywordids.length == 0) {
        keywordids.push("1");
    }*/
    messageflow.keywordids = keywordids  //Add keyword  , keyword is empty if no        //keyword is created for this message                  

    var arrcountry = messflowid.split("_");
    messageflow.countryid = arrcountry[0];  //countryid is the same as its country preference
    messageflow.languageid = arrcountry[1]; //languageid is the same as its country preference                      
    messageflow.mediaid = arrcountry[2]; //media is the same as its country preference
    return messageflow;
}
$(document).ready(function () {
    if (getURLParameter("id").toString() != "null") {
        //edit mode
        Text2.id = getURLParameter("id");
        getTextInstance(getURLParameter("id"), getURLParameter("type"));
        if (location.hash == "#copy") {
            $('.content_right_poll .title').html('New Win');
            $("#btnSave").find(".cus_button_mid").html("Save");
        }
        else {
            $("#btnSave").find(".cus_button_mid").html("Update");
            $('.content_right_poll .title').html('Edit Win');
        }
    } else {
        $("#btnSave").find(".cus_button_mid").html("Save");
    }
    $("#num_1").attr("disabled", "disabled");
    getListCampain();
    getListMessagesType();
    //getListAudience();

    $('#btnAudience').click(function (event) {
        event.stopPropagation();
        if ($('#countries0').css('display') == 'none') {
            $('#countries0').show();
        } else {
            $('#countries0').hide();
        }
        $(document).click(function () {
            if ($('#countries0').css('display') != 'none') {
                $('#countries0').hide();
            }
        });
        $('#countries0').click(function (event) {
            event.stopPropagation();
        });
        $('#sl_campaign').change(function () {
            getListAudience(true);
        });
    });
    $("#btnSaveKeyWord").click(function () {
        if ($("#btnSaveKeyWord .cus_button_mid").html() == "Update") {
            var keyword = new Object();
            keyword.id = $("#make_keyword").attr("keywordid");
            var messagelist = new Array();
            var compId = $("#make_keyword").attr("compid");
            keyword.name = $('#make_keyword').attr("keywordname");
            $("#make_keyword_detail").find(".messagesflowtype").each(function () {
                if ($(this).find(".countable").val() != "") {
                    var message1 = new Object();
                    message1.messageflowtypeid = $(this).attr("value"); // message type id
                    message1.messagebody = $(this).find(".countable").val(); // message body
                    messagelist.push(message1); //add message1 to keyword object    
                }
            });
            keyword.userid = userId;
            keyword.messagelist = messagelist;

            $.ajax({
                url: gb_servicePath + 'Keyword/Update.json',
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(keyword),
                "dataType": 'json',
                success: function (data) {
                    if (json1.StatusCode == 200) {

                    }
                }
            });
            $('#make_keyword').jqmHide();
            return true;

        }
        if (validateKeyword()) {
            $('#make_keyword').jqmHide();
            $.ajax({
                url: gb_servicePath + "/keyword/create.json",
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(buildKeyWorldCollection()),
                "dataType": 'json',
                success: function (data) {
                    // alert('ok');
                    //now add new keyword to messages flow
                    var o = $("#btKeywordTemp").clone();
                    /*  $(o).attr("value", data.Id);
                    $(o).find(".key_button_mid").html($("#txtKeyword").val());*/
                    $(o).attr("value", data.ReturnData.Id);
                    $(o).find(".key_button_mid").html(data.ReturnData.Name);
                    $(o).find(".btparent").removeClass("disable");
                    $(o).css("display", "block");
                    $(o).attr("id", "btKeyword" + data.ReturnData.Id);
                    $("#mess_detail_" + $("#make_keyword").attr("messflowid")).find(".keywordcollection").append(o);
                    $(o).find(".key_button_right").click(function () {
                        if (!$(this).parent().hasClass("disable")) {
                            removeKeyword($(this).prev().attr("id"), userId, getURLParameter("id"));
                            $(this).parent().parent().remove();
                        }
                    });

                },
                error: function (jqXHR, textStatus) {

                    alert("Error in GEMAPI/keyword/create.json");

                    /*var o = $("#btKeywordTemp").clone();
                    $(o).attr("value", "3");
                    $(o).find(".key_button_mid").html("testttt");
                    $(o).css("display", "block");
                    $("#mess_detail_" + $("#make_keyword").attr("messflowid")).find(".keywordcollection").append(o);
                    $(o).find(".key_button_right").click(function () {
                    if (!$(this).parent().hasClass("disable")) {
                    $(this).parent().parent().remove();
                    }
                    });*/

                }
            });
        }
    });
    $('#btn_SaveMessage').click(function () {
        //        jConfirm('Do you want to save messages?', 'Confirmation Dialog', function (r) {
        //            if (r) {
        //call save messages function
        var url;
        if ($("#btnSave").find(".cus_button_mid").html() == "Save") {
            url = "/messageflow/create.json";
        }
        if ($("#btnSave").find(".cus_button_mid").html() == "Update") {
            url = "/messageflow/update.json";
        }
        $("#messflows").find(".mess_detail").each(function () {
            if ($(this).attr("id") != "mess_detail_temp") {
                var flowid = $(this).attr("messflowid");
                if ($("#btnSave").find(".cus_button_mid").html() == "Update") {
                    iD = $("#mess_detail_" + flowid).find(".textarea_enable").attr("instanceid");
                    url = "/messageflow/update/" + iD + ".json";
                }
                if (flowid != undefined) {
                    $.ajax({
                        url: gb_servicePath + url,
                        crossDomain: "true",
                        type: "POST",
                        contentType: 'application/json; charset=utf-8',
                        traditional: true,
                        data: JSON.stringify(buildMessageFlowCollection(flowid)),
                        "dataType": 'json',
                        success: function (data) {
                            if ($("#btnSave").find(".cus_button_mid").html() != "Update") {
                                var oMess = new Object();

                                oMess.Id = data.ReturnData.Id;
                                oMess.countryId = data.ReturnData.Country.Id;
                                oMess.mediaId = data.ReturnData.Media.Id;
                                oMess.languageId = data.ReturnData.Language.Id;

                                var messfid = oMess.countryId + "_" + oMess.languageId + "_" + oMess.mediaId;
                                var messageflow = new Object();
                                messageflow.messagebody = $("#mess_detail_" + messfid).find("textarea").val();
                                messageflow.messageflowtypeid = "1"; // Here messageflowtypeid is 1 (alert msgs; it's 5 for keyword msgs)

                                var keywordids = new Array();
                                var keywordvalues = new Array();
                                $("#mess_detail_" + messfid).find(".button_b").each(function () {
                                    if ($(this).attr("id") != "btKeywordTemp") {
                                        keywordids.push($(this).attr("value"));
                                        keywordvalues.push($(this).find(".key_button_mid").html());
                                    }
                                });

                                if (keywordids.length == 0) {
                                    keywordids.push("1");
                                }

                                oMess.messagesBody = messageflow.messagebody;
                                // oMess.messageflowType = { Id: val.MessageflowType.Id, Name: val.MessageflowType.Name };
                                // oMess.Name = val.Name;
                                oMess.keywordlist = keywordids;
                                oMess.keywordvalues = keywordvalues;
                                arrMessagesFlows[messfid] = oMess;

                            }
                            else {
                                //
                                $("#messflows").find(".mess_detail").each(function (val) {

                                    if ($(this).attr('id') != "mess_detail_temp") {
                                        var messfid = $(this).attr("messflowid");
                                        //bind messagesbody
                                        arrMessagesFlows[messfid].messagesBody = $(this).find("textarea").val();
                                        //bind new keywordlist
                                    }
                                });

                            }
                            $('.edit_disable').css('display', 'block');
                            $('.edit_enable').css('display', 'none');
                            $('.mess_detail textarea').attr('disabled', 'disabled');
                            $('.mess_detail textarea').removeClass('textarea_enable');
                            $('.itemfilter').show();
                            $('.btn_unleashed').hide();
                            $('.btn_freetix').hide();
                            $('#btn_SaveMessage').addClass('hide');
                            $('#btn_Cancel').addClass('hide');
                            $('#btn_Edit').removeClass('hide');
                            $(".btparent").addClass("disable");
                            $(".btparent").removeClass("width_close");

                            $('#messages').addClass('hide');
                            $('.row_hide').addClass('hide');
                            $('.rows').removeClass("hover");
                            $('.list_row').jScrollPane({ animateScroll: true });
                            //alert('ok');
                            //jAlert('Save messages success', 'Alert Dialog');
                            $('#error_mess').css('display', 'none');
                        },
                        error: function (jqXHR, textStatus) {
                            $('#error_mess').css('display', 'block');
                            $('#error_mess').html('Messages should be entered');
                            //jAlert('Save messages false', 'Alert Dialog');
                            //alert("Error in GEMAPI/keyword/create.json");
                        }
                    });
                }
            }
        });
        //            } else {
        //                //do anything else
        //            }
        //        });
    });
    $('#cbWin').change(function () {

        var val = $(this).find(":selected").text();
        if (val == 'Timed win') {
            $("#num_1").attr("disabled", "disabled");
            $("#OddDec").attr("disabled", "disabled");
            $("#OddInc").attr("disabled", "disabled");
            $('#radio1').attr("disabled", true);
            $('#radio1').parent().css("color", "#cccccc");
            $('#radio1').parent().removeClass("r_on");
            $('#firstDec').attr("disabled", "disabled");
            $('#firstInc').attr("disabled", "disabled");
            $('#span_first').css("color", "#cccccc");
            var selectionType = $("input:radio[name='selection']:checked").val();
            if (selectionType == 1) { // radom
                $('.text_input_number').attr("disabled", "disabled");
                $('.text_input_number').css('color', '#ccc');
            } else if (selectionType == 2) { //Frist
                $('#list_now').find('.text_input_number').attr("disabled", "disabled");

            } else if (selectionType == 3) { //Every            
                $('.text_input_level').attr('disabled', 'disabled');
                $('.text_input_level').css('color', '#ccc');
                $('.text_input_number').attr('disabled', 'disabled');
                $('.text_input_number').css('color', '#ccc');
                $('#add_lv').addClass('hide');
                $('#add_lv_dis').removeClass('hide');
            }
        }
        else {

            $("#num_1").removeAttr("disabled");
            $("#OddDec").removeAttr("disabled");
            $("#OddInc").removeAttr("disabled");
            //$('#radio1').removeAttr("disabled");
            $('#radio1').attr("disabled", false);
            $('#radio1').parent().css("color", "#595959");
            $('#firstDec').removeAttr("disabled");
            $('#firstInc').removeAttr("disabled");
            $('#span_first').css("color", "#595959");
            //            if (val == 'Timed win') {
            //                //disable opps
            //                $('.text_input_number').attr("disabled", "disabled");
            //                $('.text_input_number').css('color', '#ccc');
            //                //document.getElementById("Text1").disabled = true;
            //            } else {
            $('.text_input_number').removeAttr("disabled");
            $('.text_input_number').css('color', '#595959');
            //}
            var selectionType = $("input:radio[name='selection']:checked").val();
            if (selectionType == 1) { // radom

            } else if (selectionType == 2) { //Frist
                if ($('.text_input_level').attr('disabled') == true) {
                    $('.text_input_level').removeAttr('disabled');
                    $('.text_input_level').css('color', '#595959');

                }
                if ($('.text_input_number').attr('disabled') == true) {
                    $('.text_input_number').removeAttr('disabled');
                    $('.text_input_number').css('color', '#595959');
                }
                if ($('#add_lv').hasClass('hide')) {
                    $('#add_lv').removeClass('hide');
                    $('#add_lv_dis').addClass('hide');
                }
            } else if (selectionType == 3) { //Every            
                $('.text_input_level').attr('disabled', 'disabled');
                $('.text_input_level').css('color', '#ccc');
                $('.text_input_number').attr('disabled', 'disabled');
                $('.text_input_number').css('color', '#ccc');
                $('#add_lv').addClass('hide');
                $('#add_lv_dis').removeClass('hide');
            }
        }

    });
    //Radom
    $('#radio0').click(function () {
        var val = $('#cbWin').find(":selected").text();


        $('#add_lv').addClass('hide');
        $('#add_lv_dis').removeClass('hide');
        if ($('.text_input_level').attr('disabled') == true) {
            $('.text_input_level').removeAttr('disabled');
            $('.text_input_level').css('color', '#595959');
        }


        var selectionType = $("input:radio[name='selection']:checked").val();
        if (selectionType == 1) { // radom

        } else if (selectionType == 2) { //Frist

        } else if (selectionType == 3) { //Every            

        }
    });
    //Frist
    $('#radio1').click(function () {
        var val = $('#cbWin').find(":selected").text();
        if (val == 'Timed win') {
            //disable opps
            $(this).attr('checked', false);
            $(this).attr("disabled", "disabled");
            $('.text_input_number').attr("disabled", "disabled");
            $('.text_input_number').css('color', '#ccc');
            //document.getElementById("Text1").disabled = true;
        } else {
            //$('.text_input_number').removeAttr("disabled");
            $('.text_input_number').attr("disabled", "disabled");
            $('.text_input_number').css('color', '#595959');
        }
        $('#list_now').find('.text_input_number').attr("disabled", "disabled");
        //        if ($('.text_input_level').attr('disabled') == true) {
        //            //$('.text_input_level').removeAttr('disabled');
        //            $('.text_input_level').attr('disabled', false);
        //            $('.text_input_level').css('color', '#fff');
        //        }
        //        if ($('.text_input_number').attr('disabled') == true) {
        //            $('.text_input_number').attr('disabled', false);
        //            $('.text_input_number').css('color', '#fff');
        //        }
        //        if ($('#add_lv').hasClass('hide')) {
        //            $('#add_lv').removeClass('hide');
        //            $('#add_lv_dis').addClass('hide');
        //        }

    });
    //every
    $('#radio2').click(function () {
        //var val = $(this).find(":selected").text();
        $('.text_input_level').attr('disabled', 'disabled');
        $('.text_input_level').css('color', '#ccc');
        $('.text_input_number').attr('disabled', 'disabled');
        $('.text_input_number').css('color', '#ccc');
        $('#add_lv').addClass('hide');
        $('#add_lv_dis').removeClass('hide');
    });



    $('.txt_time').datetimeEntry({ datetimeFormat: 'H:M', spinnerImage: '' });
    $('.txt_date').datetimeEntry({ datetimeFormat: 'O/D/Y', spinnerImage: '' });
    $('#btnOk_confirm1').click(function () {
        var divid = $("#listCountries").find(".hover").attr("id");
        var countryId = divid.substring(12, divid.length);
        //remove from arrCurrentCountry
        for (var i = 0; i < arrCurrentCountry.length; i++) {
            if (countryId = arrCurrentCountry[i].Country.Id) {
                arrCurrentCountry.splice(i, 1);
                break;
            }
        }
        $("#listCountries").find(".hover").remove();
        $('#box_confirm').jqmHide();
        refreshScrollbarListCountry();
        //$.fancybox.close();
    });

    $('#btnOk_confirm2').click(function () {
        $('div.selected').remove();
        $('#box_confirm2').jqmHide();
        //$('.scroll-pane').jScrollPane({ animateScroll: true });
    });
    $('.btn_unleashed').click(function () {
        $(this).remove();
    });
    $('.btn_freetix').click(function () {
        $(this).remove();
    });

    $('.btn_delete').click(function () {
        $(this).parent().addClass('selected');
    });
    $('.countable').jqEasyCounter({
        'maxChars': 500,
        'maxCharsWarning': 161,
        'msgFontSize': '11px',
        'msgFontColor': '#595959',
        'msgTextAlign': 'right',
        'msgWarningColor': '#F00',
        'msgAppendMethod': 'insertBefore'
    });
    $('.jqEasyCounterMsg').corner();

    $('.rows').click(function () {
        $('.rows').removeClass('hover');
        $(this).addClass('hover');
        $('.row_hide').addClass('hide');
        $(this).find('.row_hide').removeClass('hide');
        $('.list_row').jScrollPane({ animateScroll: true });
    });
    $('#make_keyword').css('right', ($(window).width() - 1100) / 2 + 120);
    $('#make_keyword').jqm({ trigger: '.jqModal' });
    $('#box_confirm').jqm({ trigger: '.i_delete' });
    $('#box_confirm2').jqm({ trigger: '.btn_delete' });
    $('#box_confirm2').jqmAddClose($('#btnCancel_confirm2'));
    $('#make_keyword').jqmAddClose($('.btn_Close'));
    $('#make_keyword').jqmAddClose($('.btn_Cancel'));
    $('#box_confirm').jqmAddClose($('#btnCancel_confirm1'));
    $("#box_alert").jqm();
    $('#box_alert').jqmAddClose($('#btnOk_boxalert'));

    //$('.list_countries').jScrollPane({ animateScroll: true });

    $('.list_winners').jScrollPane({ animateScroll: true });
    $('.countries').hide();
    /* $('.btn_countries').click(function () {
    if ($('.countries').css('display') == 'none') {
    $('.countries').show();
    } else {
    $('.countries').hide();
    }
    });*/
    $("#checkall").click(function () {
        $('.case').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearall").click(function () {
        $('.case').removeAttr('checked');
        setupLabel();
    });
    $(".txt_date").datepicker({
        showOn: "button",
        buttonImage: "../images/Controls/btn_ca.png",
        buttonImageOnly: true
    });

    $('body').addClass('has-js');

    $('.label_check, .label_radio, .label_check_ip').click(function () {
        setupLabel();
    });

    setupLabel();

    $('select.select_long').customStyle();
    $('select.select_short').customStyle();

    $("#btn_AddCountries").click(function () {
        $("#sl_campaign").attr('disabled', 'disabled');
        $('#rowCountries table').css('border', 'none');
        $('#rowCountries .lang').css('color', '#595959');
        $('#rowCountries .method').css('color', '#595959');
        if ($("#box_select_countries").css("display") == "none") {
            $("#list_countries").find(".label_check").removeClass("c_on");
            getCountries();
            for (var i = 0; i < arrCurrentCountry.length; i++) {
                addCountryItemDisplay(arrCurrentCountry[i], false);
                $("#country" + arrCurrentCountry[i].Country.Id).find(".label_check").addClass("c_on");
                $("#country" + arrCurrentCountry[i].Country.Id).find(".label_check input").attr('checked', true);
            }
            $("#box_select_countries").css("display", "block");
            $('#messages').addClass('hide');
            $('.rows').removeClass('hover');
            $('.row_hide').addClass('hide');
            if ($('.rows').length > 3) {
                $('.col_method').css('width', '105px');
            }
            else {
                $('.col_method').css('width', '106px');
            }
            $('.list_row').jScrollPane({ animateScroll: true });
        } else {
            $("#box_select_countries").css("display", "none");
        }
    });

    $('.scroll-pane').jScrollPane({ animateScroll: true });
    $('#ddlrecurring').change(function () {
        if ($(this).val() == "None") {
            $('.list_recurring').addClass('hide');
        }
        if ($(this).val() == "Occurs each hour on these minutes") {
            $('.list_recurring').addClass('hide');
            $('#hour').removeClass('hide');
        }
        if ($(this).val() == "Occurs each day at these times") {
            $('.list_recurring').addClass('hide');
            $('#day').removeClass('hide');
        }
        if ($(this).val() == "Occurs each week on these days") {
            $('.list_recurring').addClass('hide');
            $('#week').removeClass('hide');
        }
        if ($(this).val() == "Occurs each month on these days") {
            $('.list_recurring').addClass('hide');
            $('#month').removeClass('hide');
        }
        if ($(this).val() == "Occurs every year on these days") {
            $('.list_recurring').addClass('hide');
            $('#year').removeClass('hide');
        }
    });
    $('#add_lv').click(function () {
        addItemNOW(null);
        $('.text_input_level').numeric();
        $('.text_input_number').numeric();

    });

    // Add first level
    $('#add_lv').trigger('click');

    //    if ($.getUrlVar('action') == 'edit') {
    //        $(".btn_Country").css("margin-top", "0px");
    //        $('label.label_check_ip input#chkActive').attr('checked', 'checked');
    //        $('label.label_check_ip').addClass('c_ip_on');
    //        $('input.text_input').val('Lunch Promo Reminder');
    //        $('#ddlrecurring').val('Occurs each month on these days');
    //        $('#ddlrecurring').trigger('change');
    //        $('div#rows0').show();
    //        $('div#rows1').show();
    //        $('div#rows2').show();
    //        $('#send_on').val('11/17/2011');
    //        $('#valid_until').val('12/29/2011');
    //    } else { // New mode
    //        //$("#listCountries").hide();
    //        // Add margin
    //        $(".btn_Country").css("margin-top", "10px");
    //    }
    $('.list_row').jScrollPane({ animateScroll: true });

    $(".icon_remove").click(function () {
        $(this).parent().remove();
        //refreshNOW();
    })

    $("#btSortCountry").find("img").rotate(180);
    $("#btSortCountry").click(function () {
        if ($(this).attr("sort").toString() == "1") {
            sortCountryTable(true);
        } else {
            sortCountryTable(false);
        }
    });

    $('.rows').click(function () {
        $('.rows').removeClass('hover');
        $(this).addClass('hover');
        $('.row_hide').addClass('hide');
        $(this).find('.row_hide').removeClass('hide');
        $('.list_row').jScrollPane({ animateScroll: true });
    });

    //});
    function toTimestamp(strDate) {
        var datum = Date.parse(strDate);
        return datum / 1000;
    }
    function validateForm() {
        var ex = true;
        if (buildWinCollection() == null) {
            ex = false;
        }
        //var camp = $('#sl_campaign').val();
        var name = $("#txtName").val();
        var senddate = $("#send_on_date").val();
        var until = $("#valid_until_date").val();
        var sendtime = $("#send_on_time").val();
        var untiltime = $("#valid_until_time").val();
        var unitname = $('#ddlperiodUnitName').val();
        var paticipan = $('#txtNumberOfParticipants').val();
        var prizee = $("#txt_prizeexpiration").val();

        var win = "";
        $("input[@name=selection]:radio").each(function () {
            //alert($(this).val());
            if ($(this).attr('checked') && !$(this).attr('disabled')) {
                win = $(this).val();
            }
        });

        var pram = 0;
        $('.text_input_level').each(function () {
            pram += parseInt($(this).val());
        });
        //alert(pram + " - " + );
        if (Date.parse(prizee) <= Date.parse(until)) {
            $('#error').html("Prize expiration should greater than valid until");
            $('#title_prizeexpiration').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        if (prizee == "") {
            $('#error').html("Prize expiration should be entered");
            $('#title_prizeexpiration').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        if (pram > parseInt($('#num_1').val()) && $('#radio1').attr('checked')) {
            $('#error').html("Number of prize levels should be lower than total number of winners");
            $('#title_winners').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }

        if (win == "") {
            $('#error').html("Please select at least one win selection");
            $('#title_win').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        if (paticipan == "") {
            $('#error').html("Number of Participants should be entered");
            $('#title_paticipant').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }

        var start_unit = toTimestamp(senddate + ' ' + $('#send_on_time').val());
        var end_unit = toTimestamp(until + ' ' + $('#valid_until_time').val());
        if (start_unit > end_unit) {
            $('#error').html("Valid until must be greater than Send on");
            $('#title_until').css('color', '#ff5050');
            $('#title_send').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            return;
        }
        if (until == "" || untiltime == "    :") {
            $('#error').html("Valid Until date and time should be entered");
            $('#title_until').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        if (senddate == "" || sendtime == "    :") {
            $('#error').html("Send on date and time should be entered");
            $('#title_send').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        if (arrCurrentCountry.length == 0) {
            $('#error').html("Please select at least one country");
            $('#rowCountries table').css('border', '1px solid #ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        //check Countries Language and Method
        if (arrCurrentCountry.length > 0) {
            var lang = 0;
            var media = 0;
            for (var j = 0; j < arrCurrentCountry.length; j++) {
                //lang = lang + arrCurrentCountry[j].Language.length; //get All language
                for (var l = 0; l < arrCurrentCountry[j].Language.length; l++) {
                    if (arrCurrentCountry[j].Language[l].selected) {
                        lang++;
                        for (var k = 0; k < arrCurrentCountry[j].Language[l].Media.length; k++) {
                            //media = media + arrCurrentCountry[j].Language[k].Media.length; //get All media
                            if (arrCurrentCountry[j].Language[l].Media[k].selected) {
                                media++;
                            }
                        }
                    }
                }

            }
            if (media == 0) {
                $('#error').html("Please select at at least one delivery method");
                $('#rowCountries .method').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
            if (lang == 0) {
                $('#error').html("Please select at at least one language for selected countries");
                $('#rowCountries .lang').css('color', '#ff5050');
                $('#error').css('color', '#ff5050');
                ex = false;
            }
        }
        if (name == "") {
            $('#error').html("Win name should be entered");
            $('#title_name').css('color', '#ff5050');
            $('#error').css('color', '#ff5050');
            ex = false;
        }
        //        else {
        //            checkUnique(name, $('select#sl_campaign option:selected').attr('id'));
        //            if ($('#error').html() == 'Win with this name already exists. Please choose another name.') {
        //                ex = false;
        //            }
        //        }
        return ex;
    }
    function checkUnique(name, campaignid) {
        //alertcolletion/list/summary.json?name=<alert name>&campaignid= <id of campaign the alert is for>
        //var ex = new Object();
        $.getJSON(gb_servicePath + 'alertcollection/list/summary.json?name=' + $("#txtName").val() + '&campaignid=' + $('select#sl_campaign option:selected').attr('id'),
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (getURLParameter("id").toString() != "null") {// if action is edit
                                if (getURLParameter("id").toString() == val.Id.toString()) {
                                    $('#error').html("Win or other alert with this name already exists. Please choose another name.");
                                    $('#title_name').css('color', '#ff5050');
                                    $('#error').css('color', '#ff5050');
                                }
                            }
                            else { // if action is create new
                                $('#error').html("Win or other alert with this name already exists. Please choose another name.");
                                $('#title_name').css('color', '#ff5050');
                                $('#error').css('color', '#ff5050');
                            }
                        });
                    }
                    else {
                        if (isBug) {
                            alert('Error in alertcollection/list/summary.json');
                        }
                    }
                });
    }
    $(".text_input_level").keypress(function () {
        $('#error').html('');
        $('#title_winners').css('color', '#595959');
    });
    $("#txt_prizeexpiration").keypress(function () {
        $('#error').html('');
        $('#title_prizeexpiration').css('color', '#595959');
    });
    $("#txtNumberOfParticipants").keypress(function () {
        $('#error').html('');
        $('#title_paticipant').css('color', '#595959');
    });
    $("#txtName").keypress(function () {
        $('#error').html('');
        $('#title_name').css('color', '#595959');
    });
    $("#send_on_date").keypress(function () {
        $('#error').html('');
        $('#title_send').css('color', '#595959');
        $('#title_until').css('color', '#595959');
    });
    $("#valid_until_date").keypress(function () {
        $('#error').html('');
        $('#title_send').css('color', '#595959');
        $('#title_until').css('color', '#595959');
    });

    $("#btnSaveAsDraft").click(function () {
        if (validateForm()) {
            $.getJSON(gb_servicePath + 'alertcollection/list/summary.json?name=' + $("#txtName").val() + '&campaignid=' + $('select#sl_campaign option:selected').attr('id'),
                function (json1) {
                    if (json1.StatusCode == 200) {
                        if (json1.ReturnData.length > 0) {
                            $.each(json1.ReturnData, function (i, val) {
                                if (getURLParameter("id").toString() != "null") {// if action is edit
                                    if (getURLParameter("id").toString() == val.Id.toString()) {
                                        $('#error').html("Win or other alert with this name already exists. Please choose another name.");
                                        $('#title_name').css('color', '#ff5050');
                                        $('#error').css('color', '#ff5050');
                                        return false;
                                    }
                                }
                                else { // if action is create new
                                    $('#error').html("Win or other alert with this name already exists. Please choose another name.");
                                    $('#title_name').css('color', '#ff5050');
                                    $('#error').css('color', '#ff5050');
                                    return false;
                                }
                            });
                        }
                        else {
                            var win = new buildWinCollection();
                            win.approvalstatusid = 2;
                            $.ajax({
                                url: gb_servicePath + "/win/create.json",
                                crossDomain: "true",
                                type: "POST",
                                contentType: 'application/json; charset=utf-8',
                                traditional: true,
                                data: JSON.stringify(win),
                                "dataType": 'json',
                                success: function (data) {
                                    window.location.href = '../Source/WinLibrary';
                                },
                                error: function (jqXHR, textStatus) {
                                    if (isBug) {
                                        alert("Error in EMAPI/win/create.json");
                                    }
                                }
                            });
                        }
                    }
                    else {
                        if (isBug) {
                            alert('Error in alertcollection/list/summary.json');
                        }
                    }
                });
        }
    });
    $("#btnSave").click(function () {
        if (validateForm()) {
            if ($("#btnSave").find(".cus_button_mid").html() == "Save") {

                $.ajax({
                    url: gb_servicePath + "/win/create.json",
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(buildWinCollection()),
                    "dataType": 'json',
                    success: function (data) {
                        window.location.href = '../Source/WinLibrary';
                    },
                    error: function (jqXHR, textStatus) {
                        if (isBug) {
                            alert("Error in EMAPI/win/create.json");
                        }
                    }

                });

            } else {

                //
                $.ajax({
                    url: gb_servicePath + "/win/update.json",
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(buildWinCollection()),
                    "dataType": 'json',
                    success: function (data) {
                        window.location.href = '../Source/WinLibrary';
                    },
                    error: function (jqXHR, textStatus) {
                        if (isBug) {
                            alert("ah, error");
                        }
                    }

                });
            }
        }
        else {
            return false;
        }
    });

    //for country box

    //close messages box
    $('#messages-close').click(
        function () {
            jConfirm('Do you want to close this dialog?', 'Confirmation Dialog', function (r) {
                if (r) {
                    $('.edit_disable').css('display', 'block');
                    $('.edit_enable').css('display', 'none');
                    $('.mess_detail textarea').attr('disabled', 'disabled');
                    $('.mess_detail textarea').removeClass('textarea_enable');
                    $('.itemfilter').show();
                    $('.btn_unleashed').hide();
                    $('.btn_freetix').hide();
                    $('#btn_SaveMessage').addClass('hide');
                    $('#btn_Cancel').addClass('hide');
                    $('#btn_Edit').removeClass('hide');
                    $(".btparent").addClass("disable");
                    $(".btparent").removeClass("width_close");


                    $('#messages').addClass('hide');
                    $('.rows').removeClass('hover');
                    $('.row_hide').addClass('hide');
                    if ($('.rows').length > 3) {
                        $('.col_method').css('width', '105px');
                    }
                    else {
                        $('.col_method').css('width', '105px');
                    }
                    $('.list_row').jScrollPane({ animateScroll: true });
                } else {
                    //do anything else
                }
            });
        }
    );
    //Cancel box messages
    $('#btn_Cancel').click(function () {
        $('.edit_disable').css('display', 'block');
        $('.edit_enable').css('display', 'none');
        $('.mess_detail textarea').attr('disabled', 'disabled');
        $('.mess_detail textarea').removeClass('textarea_enable');
        $('.itemfilter').show();
        $('.btn_unleashed').hide();
        $('.btn_freetix').hide();
        $('#btn_SaveMessage').addClass('hide');
        $('#btn_Cancel').addClass('hide');
        $('#btn_Edit').removeClass('hide');
        $(".btparent").addClass("disable");
        $(".btparent").removeClass("width_close");


        $('#messages').addClass('hide');
        $('.rows').removeClass('hover');
        $('.row_hide').addClass('hide');
        if ($('.rows').length > 3) {
            $('.col_method').css('width', '105px');

        }
        else {
            $('.col_method').css('width', '106px');
        }
        $('.list_row').jScrollPane({ animateScroll: true });
    });

});

function addItemNOW(datarow) {
    
    var o = $(".nowTemp").clone();
    if (datarow) {
        $(o).find("b").html(addOrdinalNumberSuffix(datarow.Level) + ' prize level');
        $(o).attr("id", "now_" + datarow.Level);
        $(o).find("input#Text1").val(datarow.Odds);
        $(o).find("input#Text1").attr('id', 'odds_' + datarow.Level);
        $(o).find("input#Text3").val(datarow.Number);
        $(o).find("input#Text3").attr('id', 'prize_text_' + datarow.Level);
    }
    else {
        $(o).find("b").html(addOrdinalNumberSuffix($("#list_now").find(".form_rows").length) + ' prize level');
        $(o).attr("id", "now_" + $("#list_now").find(".form_rows").length);
        $(o).find("input#Text1").attr('id', 'odds_' + $("#list_now").find(".form_rows").length);
        $(o).find("input#Text3").attr('id', 'prize_text_' + $("#list_now").find(".form_rows").length);
    }

    $(o).addClass('nows');
    $(o).removeClass('nowTemp');

    $("#list_now").append(o);
    $('.list_winners').jScrollPane({ animateScroll: true });
    //$(o).css("width", $(o).find(".filertext").outerWidth() + 25);

    //add event listener
    $(o).find(".icon_remove").click(function () {
        $(this).parent().remove();
        $('.list_winners').jScrollPane({ animateScroll: true });
        refreshNOW();
    });
    $(".text_input_1").numeric();
    setformfieldsize($('.text_input_1'), 6, '');
}
function refreshNOW() {
    $("#list_now").find(".form_rows").each(function (index) {
        //alert(index);
        $(this).find("b").html(addOrdinalNumberSuffix(index) + ' prize level');
        $(this).attr('id', 'now_' + index);
    });
}
function addOrdinalNumberSuffix(num) {
    var arr = [11, 12, 13];

    if (jQuery.inArray((num % 100), arr)) {
        switch (num % 10) {
            // Handle 1st, 2nd, 3rd       
            case 0: if (num > 0) { return num + 'th'; } else { return 1 + 'st'; }
            case 1: return num + 'st';
            case 2: return num + 'nd';
            case 3: return num + 'rd';
        }
    }
    return num + 'th';
}
function checkNumberValue(id) {
    var num = document.getElementById(id).value;
    if (num > 0) {
        document.getElementById(id).value = num - 1;
    }
}

function buildWinCollection() {
    var Text2 = new Object();
    if ($("#btnSave").find(".cus_button_mid").html() == "Update") {
        Text2.Text2Id = getURLParameter("id");
    }
    Text2.name = $('#txtName').val(); ;
    Text2.campaignid = parseInt($("#campaign_selection #sl_campaign").find("option:selected").attr("id"));
    Text2.starttime = dateFormat($("#send_on_date").val(), 'isoDate') + " " + $("#send_on_time").val();
    Text2.endtime = dateFormat($("#valid_until_date").val(), 'isoDate') + " " + $("#valid_until_time").val();
    Text2.isrecurring = false;
    if ($(".label_check_ip").hasClass("c_ip_on")) {
        Text2.isactive = true;
    } else {
        Text2.isactive = false;
    }
    Text2.messageflowids = new Array(); ;
    Text2.createdby = userId;
    Text2.approvalstatusid = 1;
    Text2.componentid = 5;
    var arrAudienceId = new Array();
    $("#list_audience").find(".list_count").each(function () {
        if ($(this).find(".label_check").hasClass("c_on")) {
            arrAudienceId.push($(this).attr("id"));
        }

    });
    if (arrAudienceId.length == 0) {
        $('#error').html("Audiences should be selected ");
        return null;
    }
    Text2.audienceids = arrAudienceId;
    //Text2.audienceids = [$("#audience_selection").find("option:selected").attr("id")];

    //    Text2.countrymediapreference = new Array();
    //    var pref = new Object();
    //    var ctryPref = new Object();
    //    ctryPref.countryid = "5";
    //    ctryPref.id = "1";
    //    ctryPref.languageid = "1";
    //    ctryPref.timezoneid = "30";
    //    pref.countrypreference = ctryPref;
    //    pref.mediaid = "1";
    var missingMessagesFlow = false;
    Text2.countrymediapreference = new Array();
    $("#listCountries").find(".jspPane").find(".rows").each(function () {
        if ($(this).attr("id") != "country_temp") {
            var o = jQuery.parseJSON($(this).attr("data"));
            for (var i = 0; i < o.Language.length; i++) {
                if (o.Language[i].selected == true) {
                    var medias = o.Language[i].Media;
                    for (var j = 0; j < medias.length; j++) {
                        if (medias[j].selected == true) {
                            var pref = new Object();
                            var ctryPref = new Object();
                            ctryPref.countryid = o.Country.Id
                            ctryPref.id = o.Language[i].CountryPreId;
                            ctryPref.languageid = o.Language[i].Id;
                            ctryPref.timezoneid = o.Timezone.Id;
                            pref.countrypreference = ctryPref;
                            pref.mediaid = medias[j].Id;
                            Text2.countrymediapreference.push(pref);
                            if (arrMessagesFlows[o.Country.Id + "_" + o.Language[i].Id + "_" + medias[j].Id] != undefined) {
                                Text2.messageflowids.push(arrMessagesFlows[o.Country.Id + "_" + o.Language[i].Id + "_" + medias[j].Id].Id);
                            } else {
                                // alertcollection.messageflowids.push("1");
                                $('#error').html("Message for each (country,language,method) should be entered ");
                                $('#error').css('color', '#ff5050');
                                missingMessagesFlow = true;
                                return null;
                            }
                        }
                    }
                }
            }
        }

    });


    Text2.type = "Win";
    Text2.participatorestimation = parseInt($('#txtNumberOfParticipants').val());
    Text2.wintype = $("#cbWin option:selected").attr("name"); ; //(1 timed win, 2 instance win)
    Text2.prizeexpiration = dateFormat($("#txt_prizeexpiration").val(), 'isoDate');
    Text2.winselecttype = $("input:radio[name='selection']:checked").val();  //(1 random, 2 first, 3 every)
    Text2.winselectvalue = $("input:radio[name='selection']:checked").val();
    Text2.periodUnitName = $("#ddlperiodUnitName option:selected").val();  //(Day, Week, Month,Duration of the sweepstakes)
    var prize = new Array();

    $('#list_now .nows').each(function (index) {
        var prize1 = new Object();
        prize1.prizelevel = (index + 1);
        prize1.number = $('#now_' + (index + 1)).find('input.text_input_level').val();
        prize1.odd = $('#now_' + (index + 1)).find('input.text_input_number').val();
        prize.push(prize1);
    });
    Text2.prize = prize;

    if (missingMessagesFlow) {
        return null;
    } else {
        return Text2;
    }
}
function editKeyword(id, KeyworkVal) {
    $('#make_keyword .header_box_campain').html('Edit Keyword');
    $('#make_keyword').attr("keyWordId", id);

    $('#make_keyword_').find(".countable").val("");
    $('#errorMakekeyword').html("");
    $("#txtKeywordOptOut").val("");
    $('#make_keyword div#keyword').hide();
    $('#txtKeyword').parent().css("display", "none");
    $('#txtKeyword').val("");
    $(".keyword .cus_input").css("display", "none");
    $("#B1").parent().parent().next().css("display", "none");
    $("#B1").parent().parent().next().next().css("display", "none");
    $("#B1").parent().parent().css("display", "none");
    $("#btnSaveKeyWord .cus_button_mid").text("Update");
    $.getJSON(gb_servicePath + '/keyword/ID/' + id + '.json', {},
        function (json2) {
            if (json2.StatusCode == 200) {
                var data = json2.ReturnData;
                for (i = 0; i < data.FollowUpMessageFlowList.length; i++) {
                    $("#messagestype" + data.FollowUpMessageFlowList[i].MessageflowType.Id.toString() + " textarea").val(data.FollowUpMessageFlowList[i].Messagebody);

                }
                $('#keyword').css("display", "block");
                $('#keyword').css("background-color", "#eee");
                $('#keyword').css("color", "#333");
                $('#keyword').html(data.Name);
                $('#make_keyword').attr("keywordname", data.Name);
                $('#make_keyword').attr("compid", data.Component.Id);
                $('#make_keyword').jqmShow();
            }
        });
}

function getCountries() {
    // arrCountry.length = 0;
    $("#list_countries .list_count").css("display", "none");
    $.ajax({ url: gb_servicePath + '/campaign/ID/' + $("#sl_campaign").find(":selected").attr("id") + '.json',
        dataType: 'json',
        async: false,
        success: function (json1) {
            var data = json1.ReturnData;
            for (i = 0; i < data.Countrys.length; i++) {
                $("#country" + data.Countrys[i].Id.toString()).css("display", "block");
            }
        }
    });


}
